package directory

import (
	"context"
	"regexp"
	"strings"

	"mall/common/globalkey"
	"mall/service/attachment/rpc/attachmentclient"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/utils/pointy"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateDirectoryLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateDirectoryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateDirectoryLogic {
	return &CreateDirectoryLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateDirectoryLogic) CreateDirectory(req *types.CreateMediaDirectoryReq) (resp *types.BaseMsgResp, err error) {
	if req.Path == nil || len(strings.TrimSpace(*req.Path)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "file.directoryPathRequired"))
	}

	userId := l.GetUserId()

	reg := regexp.MustCompile("[^-A-Za-z0-9_.]")
	path := reg.ReplaceAllString(*req.Path, "_") // filter out all non word characters

	res, err := l.svcCtx.AttachmentRpc.BackendCreateFile(l.ctx, &attachmentclient.FileInfo{
		AltText:  req.Title,
		Excerpt:  req.Excerpt,
		Path:     &path,
		UserId:   &userId,
		ParentId: req.ParentId,
		Type:     pointy.GetPointer(uint32(globalkey.AttachmentTypeDirectory)),
	})
	if err != nil {
		return
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}

func (l *CreateDirectoryLogic) GetUserId() string {
	var userId string
	if val := l.ctx.Value("userId"); val != nil {
		userId = val.(string)
	}

	return userId
}
